

package com.jingdun.sport.security.util;


import com.jingdun.sport.security.service.YamiSysUser;
import com.jingdun.sport.security.service.YamiUser;
import com.jingdun.sport.security.exception.UnauthorizedExceptionBase;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 安全工具类
 *
 * @author L.cm
 */
@UtilityClass
public class SecurityUtils {
    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     */
    public YamiUser getUser() {
        Authentication authentication = getAuthentication();
        Object principal = authentication.getPrincipal();

        if (principal instanceof YamiUser) {
            return (YamiUser) principal;
        }
        throw new UnauthorizedExceptionBase("无法获取普通用户信息");
    }

    /**
     * 获取用户
     */
    public Boolean isUser() {
        Authentication authentication = getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal instanceof YamiUser) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 获取系统用户
     */
    public YamiSysUser getSysUser() {
        Authentication authentication = getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal instanceof YamiSysUser) {
            return (YamiSysUser) principal;
        }
        throw new UnauthorizedExceptionBase("无法获取系统用户信息");
    }
}
